<template>
    <div>
        <div class="goods_head_btn">
            <a-button type="primary" @click="handleCancle" v-if="showType == 'details'">返回</a-button>
            <a-button type="primary" @click="handleCancle" v-if="showType !== 'details'">取消</a-button>
            <a-button type="danger" @click="onSubmit" v-if="showType !== 'details'">确认</a-button>
        </div>
        <a-form
            class="goods_form"
            layout="horizontal"
            :model="formState"
            :rules="rules"
            ref="formRef"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
        >
            <div class="goods-upload">
                <a-form-item :label="t('yl.goodsName')">
                    <div class="goods-upload-item">
                        <a-upload
                            v-model:file-list="fileList"
                            name="avatar"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            :disabled="showType == 'details'"
                        >
                            <img v-if="formState.imgUrl" :src="formState.imgUrl" alt="avatar" />
                            <div v-else>
                                <loading-outlined v-if="loading"></loading-outlined>
                                <plus-outlined v-else></plus-outlined>
                            </div>
                        </a-upload>
                        <a-button @click="handMaterial('img')">素材库</a-button>
                    </div>
                    <div>注：图片容量不能超过3M</div>
                </a-form-item>
                <a-form-item :label="t('yl.goodsName')">
                    <div class="goods-upload-item">
                        <a-upload
                            v-model:file-list="fileList"
                            name="avatar"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            :disabled="showType == 'details'"
                        >
                            <img v-if="formState.imgUrl" :src="formState.imgUrl" alt="avatar" />
                            <div v-else>
                                <loading-outlined v-if="loading"></loading-outlined>
                                <plus-outlined v-else></plus-outlined>
                            </div>
                        </a-upload>
                        <a-button @click="handMaterial('video')">素材库</a-button>
                    </div>
                    <div>注：视频容量不能超过3M</div>
                </a-form-item>
            </div>

            <!-- 商品名称 -->
            <a-form-item :label="t('yl.goodsName')" name="name">
                <a-input v-model:value="formState.name" :disabled="showType == 'details'" />
            </a-form-item>
            <!-- 商品编码 -->
            <a-form-item :label="t('yl.skuCode')" name="skuCode">
                <a-input v-model:value="formState.skuCode" :disabled="showType == 'details'" />
            </a-form-item>
            <!-- 品类名称 -->
            <a-form-item :label="t('yl.skuSpecsId')" name="skuSpecsId">
                <a-select v-model:value="formState.skuSpecsId" :disabled="showType == 'details'">
                    <a-select-option :value="item.id" v-for="(item, index) in skuSpecsList" :key="index">{{
                        item.specsName
                    }}</a-select-option>
                </a-select>
            </a-form-item>
            <!-- 库存 -->
            <a-form-item :label="t('yl.stock')" name="stock">
                <a-input v-model:value="formState.stock" :disabled="showType == 'details'" />
            </a-form-item>
            <!-- 商品二维码 -->
            <a-form-item :label="t('yl.qrCode')" name="qrCode">
                <a-input v-model:value="formState.qrCode" :disabled="showType == 'details'" />
            </a-form-item>
            <!-- 零售价 -->
            <a-form-item :label="t('yl.commonPrice')" name="commonPrice">
                <a-input-number
                    style="width: 100%"
                    id="inputNumber"
                    :disabled="showType == 'details'"
                    v-model:value="formState.commonPrice"
                    :min="1"
                    :max="9999"
                />
            </a-form-item>
            <!-- 会员价 -->
            <a-form-item :label="t('yl.memberPrice')" name="memberPrice">
                <a-input-number
                    style="width: 100%"
                    id="inputNumber"
                    :disabled="showType == 'details'"
                    v-model:value="formState.memberPrice"
                    :min="1"
                    :max="9999"
                />
            </a-form-item>
            <!-- 市场价 -->
            <a-form-item :label="t('yl.marketPrice')" name="marketPrice">
                <a-input-number
                    style="width: 100%"
                    id="inputNumber"
                    :disabled="showType == 'details'"
                    v-model:value="formState.marketPrice"
                    :min="1"
                    :max="9999"
                />
            </a-form-item>
            <!-- 促销价 -->
            <a-form-item :label="t('yl.bargainPrice')" name="bargainPrice">
                <a-input-number
                    style="width: 100%"
                    id="inputNumber"
                    v-model:value="formState.bargainPrice"
                    :min="1"
                    :disabled="showType == 'details'"
                    :max="9999"
                />
            </a-form-item>
            <a-form-item
                :label="store.getters.lang == 'zh' ? item.name : item.enName"
                :name="item.code"
                v-for="(item, index) in formState.skuStr"
                :key="index"
            >
                <a-date-picker
                    style="width: 100%"
                    v-model:value="item[item.code]"
                    v-if="item.dataType == '3'"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    :disabled="showType == 'details'"
                />
                <a-date-picker
                    style="width: 100%"
                    v-model:value="item[item.code]"
                    v-if="item.dataType == '4'"
                    valueFormat="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    :disabled="showType == 'details'"
                />
                <a-input
                    v-if="item.dataType == '2'"
                    v-model:value="item[item.code]"
                    :name="item.code"
                    :disabled="showType == 'details'"
                />
                <a-input-number
                    style="width: 100%"
                    v-if="item.dataType == '1'"
                    id="inputNumber"
                    :disabled="showType == 'details'"
                    v-model:value="item[item.code]"
                    :min="1"
                    :max="10"
                />
            </a-form-item>
        </a-form>
        <material-model
            :visible="visible"
            :loading="confirmLoading"
            :user="selectedRow"
            @cancle="handleMaterialCancle"
            @submit="handleSubmit"
        ></material-model>
    </div>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, watch, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import materialModel from './materialModel.vue';
import { getskuDictMerchant, getskuDict } from '@/api/system';

import { useStore } from 'vuex';
import { addskuGoodsSku, getCetegory, putskuGoodsSku } from '@/api/goods';
import { Console } from 'console';

// import { RootState } from '@/store';
// interface formState {
//     name: string;
//     deptSort: string | number;
//     isTop: string;
//     enabled: string | boolean;
//     id: undefined | string | number;
//     pid?: undefined | string | number;
//     subCount?: '0';
// }
// 表单校验规则
const initRules = (t: fn) => {
    return {
        name: [{ required: true, message: t('yl.goodsName'), trigger: 'blur' }],
        skuCode: [{ required: true, message: t('yl.skuCode'), trigger: 'blur' }],
        skuSpecsId: [{ required: true, message: t('yl.skuSpecsId'), trigger: 'blur', type: 'number' }],
    };
};

export default defineComponent({
    name: 'listForm',
    components: { materialModel },
    props: {
        row: {
            type: Object,
        },
        showType: {
            type: String,
            default: () => '',
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        console.log(props.row);
        const store = useStore();
        const { t } = useI18n();
        const skuSpecsList: any = ref([]);
        const formState: any = reactive({
            // 	促销价
            bargainPrice: null,
            // 	标准价
            commonPrice: null,
            // 商品id
            id: '',
            // 	商品图片地址
            imgUrl: '',
            // 	市场价
            marketPrice: null,
            // 会员价
            memberPrice: null,
            // 商户编码
            merchantCode: '',
            // 	商品名称
            name: '',
            // 商品二维码
            qrCode: '',
            // 商品的sku码
            skuCode: '',
            // 	商品品类id
            skuSpecsId: null,
            // 	商户自定义的商品属性
            skuStr: [],
            // 商品库存
            stock: '',
            // 	商品视频地址
            videoUrl: '',
        });
        const fileList = ref([]);
        const loading = ref<boolean>(false);
        const imageUrl = ref<string>('');
        const showType = computed(() => props.showType);

        const material = reactive({
            type: '',
            url: '',
            visible: false,
        });
        const {
            bargainPrice,
            commonPrice,
            id,
            imgUrl,
            marketPrice,
            memberPrice,
            merchantCode,
            name,
            qrCode,
            skuCode,
            skuSpecsId,
            skuStr,
            stock,
            videoUrl,
        } = props.row as NormalObj;
        if (JSON.stringify(props.row) !== '{}') {
            console.log('ddd');
            console.log(skuStr);
            formState.bargainPrice = bargainPrice;
            formState.commonPrice = commonPrice;
            formState.imgUrl = imgUrl;
            formState.marketPrice = marketPrice;
            formState.memberPrice = memberPrice;
            formState.merchantCode = merchantCode;
            formState.name = name;
            formState.qrCode = qrCode;
            formState.skuCode = skuCode;
            formState.skuSpecsId = skuSpecsId;
            formState.stock = stock;
            formState.videoUrl = videoUrl;
            formState.skuStr = skuStr;
            formState.id = id;
        }

        // 获取当前用户字典
        const skuDictList = async () => {
            console.log('2134');
            console.log(formState.skuStr.length);
            const list = await getskuDict();
            console.log(list);
            let skuStr: any = JSON.parse(JSON.stringify(formState.skuStr));
            list.forEach((i: any) => {
                var isEquals = false;
                if (skuStr && skuStr.length) {
                    for (var j = 0; j < skuStr.length; j++) {
                        if (i.code == skuStr[j].code) {
                            skuStr[j].name = i.name;
                            skuStr[j].enName = i.enName;
                            skuStr[j].dataType = i.dataType;
                            isEquals = false;
                            break;
                        } else if (i.isDefault !== 1 && skuStr[j].code !== i.code) {
                            isEquals = true;
                        }
                    }
                } else {
                    if (i.isDefault !== 1) {
                        isEquals = true;
                    }
                }

                if (isEquals) {
                    skuStr.push({
                        [i.code]: '',
                        code: i.code,
                        name: i.name,
                        enName: i.enName,
                        dataType: i.dataType,
                    });
                }
            });
            console.log(skuStr);
            formState.skuStr = skuStr;

            console.log();
        };
        // 获取table数据
        const getCetegoryData = async () => {
            const { content, totalElements } = await getCetegory();
            skuSpecsList.value = content;
        };

        onMounted(async () => {
            skuDictList();
            getCetegoryData();
        });

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                const obj: any = {};
                formState.skuStr.forEach((item: any) => {
                    obj[item.code] = item[item.code];
                });
                const data = JSON.parse(JSON.stringify(formState));
                data.skuStr = obj;

                if (showType.value === 'add') {
                    addskuGoodsSku(data).then((res) => {
                        const timer = window.setTimeout(() => {
                            emit('submit');
                        }, 1000);
                    });
                } else {
                    putskuGoodsSku(data).then((res) => {
                        const timer = window.setTimeout(() => {
                            emit('submit');
                        }, 1000);
                    });
                }
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('submit');
        };
        // 素材
        const handMaterial = (type: string) => {
            material.visible = true;
        };
        // 素材
        const handleMaterialCancle = () => {
            material.visible = false;
        };

        return {
            skuSpecsList,
            formRef,
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            fileList,
            formState,
            showType,
            t,
            rules,
            onSubmit,
            handleCancle,
            skuDictList,
            addskuGoodsSku,
            store,
            getCetegoryData,
            handMaterial,
            handleMaterialCancle,
            ...toRefs(material),
        };
    },
});
</script>
<style lang="scss" scoped>
.goods_head_btn {
    padding: 20px;
    .ant-btn {
        margin-right: 20px;
    }
}
.goods_form {
    @include flexWrap;
    width: 100%;
    .goods-upload {
        display: flex;
        width: 100%;
        .goods-upload-item {
            display: flex;
            align-items: flex-end;

            .ant-upload-picture-card-wrapper {
                width: auto;
            }
        }
    }
    .ant-form-item {
        width: 20%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
    }
}
</style>
<style>
.goods_form .ant-upload.ant-upload-select-picture-card {
    margin-bottom: 0;
}
</style>
